interface LoginResponse {
  errCode: number;
  message?: string;
  newToken?: any;
  errMsg:string
}

export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  if (!body.username || !body.password) {
    throw createError({
      statusCode: 400,
      statusMessage: "缺少必要的登录参数：username, password",
    });
  }

  const requestData = {
    clientInfo: {
      uniPlatform: "web",
      appId: "__UNI__3C0EDFA",
      deviceId: "test-device-123",
    },
    params: {
      username: body.username,
      password: body.password,
    },
    // code: body.code
  };

  try {
    const response = await $fetch<LoginResponse>(
      "https://fc-mp-dcc57d1b-9703-4fa7-bf3e-a2bebe5587bd.next.bspapp.com/IdCo/login",
      {
        method: "POST",
        body: requestData,
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    if (response.errCode === 0) {
      return {
        success: true,
        newToken: response.newToken,
        message: "登录成功",
        errCode: 0,
      };
    } else {
      return {
        success: false,
        data: null,
        message: response.errMsg || "登录失败",
        errCode: response.errCode,
      };
    }
  } catch (error: any) {
    throw createError({
      statusCode: 500,
      statusMessage: error.message || "服务器内部错误",
    });
  }
});
